package com.eazyshop.controller;


import com.eazyshop.common.pojo.Result;
import com.eazyshop.common.pojo.StatusCode;
import com.eazyshop.utils.FastDFSClient;
import com.eazyshop.utils.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/uploade")
    public Result uploadFile(MultipartFile file) throws IOException {
        // 判断文件是否存在
        if(file==null){
            throw new RuntimeException("文件不存在");
        }
        // 获得文件完整名称
        String originalFilename = file.getOriginalFilename();

        if(StringUtils.isEmpty(originalFilename)){
            throw new RuntimeException("文件不存在");
        }
        //获得文件扩展名称 不包括 .
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //获取文件内容
        byte[] bytes = file.getBytes();
        // 创建文件上传的实体类
        FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, extName);
        // 文件上传返回内容
        String[] upload = FastDFSClient.upload(fastDFSFile);

        // 封装返回结果
        String url=FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];

        return new Result(true, StatusCode.OK,"上传成功",url);


    }
}
